package com.peng.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peng.base.exception.GuliException;
import com.peng.edu.client.VodClient;
import com.peng.edu.entity.*;
import com.peng.edu.entity.frontVo.CourseFrontVo;
import com.peng.edu.entity.frontVo.CourseWebVo;
import com.peng.edu.entity.vo.CourseInfoVo;
import com.peng.edu.entity.vo.CoursePublishVo;
import com.peng.edu.mapper.CourseDescriptionMapper;
import com.peng.edu.mapper.CourseMapper;
import com.peng.edu.service.ChapterService;
import com.peng.edu.service.CourseDescriptionService;
import com.peng.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.edu.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Dengp
 * @since 2022-06-16
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService courseDescriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private VodClient vodClient;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class,Exception.class})
    public String addCourseInfo(CourseInfoVo courseInfoVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo,course);
        boolean save = this.saveOrUpdate(course);
        if (!save){
            throw new GuliException(20001,"添加课程信息失败");
        }
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setCourseId(course.getId());
        courseDescriptionService.saveOrUpdate(courseDescription);
        return course.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoId(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        Course course = this.getById(courseId);
        LambdaQueryWrapper<CourseDescription> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseDescription::getCourseId,courseId);
        CourseDescription one = courseDescriptionService.getOne(queryWrapper);
        BeanUtils.copyProperties(course,courseInfoVo);
        courseInfoVo.setDescription(one.getDescription());
        return courseInfoVo;
    }

    //根据课程id查询课程确认信息
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    @Override
    @Transactional
    public boolean removeCourse(String id) {
        this.removeById(id);
        LambdaQueryWrapper<CourseDescription> descriptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        descriptionLambdaQueryWrapper.eq(CourseDescription::getCourseId,id);
        courseDescriptionService.remove(descriptionLambdaQueryWrapper);
        LambdaQueryWrapper<Chapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapterLambdaQueryWrapper.eq(Chapter::getCourseId,id);
        chapterService.remove(chapterLambdaQueryWrapper);
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.eq(Video::getCourseId,id);
        List<Video> list = videoService.list(videoLambdaQueryWrapper);
        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getVideoSourceId()!=null){
                String s = list.get(i).getVideoSourceId();
                stringBuilder.append(s);
            }
            if (i!=(list.size()-1)){
                stringBuilder.append(",");
            }
        }
        String ids = stringBuilder.toString();
        if (ids!=null){
            vodClient.removeAliyunVideo(ids);
        }
        videoService.remove(videoLambdaQueryWrapper);
        return true;
    }

    //按照条件查询课程信息返回前端页面
    @Override
    public Map<String, Object> getCourseAll(Page<Course> pageCourse, CourseFrontVo courseFrontVo) {
        String title = null;
        String subjectId = null;
        String subjectParentId = null;
        String gmtCreateSort = null;
        String buyCountSort = null;
        String priceSort = null;
        String teacherId = null;

        if (!StringUtils.isEmpty(courseFrontVo)){
            title = courseFrontVo.getTitle();
            subjectId = courseFrontVo.getSubjectId();
            subjectParentId = courseFrontVo.getSubjectParentId();
            gmtCreateSort = courseFrontVo.getGmtCreateSort();
            buyCountSort = courseFrontVo.getBuyCountSort();
            priceSort = courseFrontVo.getPriceSort();
            teacherId = courseFrontVo.getTeacherId();
        }


        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接条件
        if (!StringUtils.isEmpty(subjectParentId)){//一级分类
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)){//二级分类
            wrapper.eq("subject_id",subjectId);
        }
        if (!StringUtils.isEmpty(buyCountSort)){//关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(priceSort)){//价格
            wrapper.orderByDesc("price");
        }
        if (!StringUtils.isEmpty(gmtCreateSort)){//最新，创建时间
            wrapper.orderByDesc("gmt_create");
        }

        baseMapper.selectPage(pageCourse, wrapper);

        List<Course> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();
        //是否有下一页
        boolean hasNext = pageCourse.hasNext();
        //是否有上一页
        boolean hasPrevious = pageCourse.hasPrevious();
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    //根据课程id获取课程详细信息
    @Override
    public CourseWebVo getBaseCourseInfo(String id) {
        CourseWebVo courseWebVo= baseMapper.getBaseCourseInfo(id);
        return courseWebVo;
    }


}
